#ifndef __DatabaseCreator__
#define __DatabaseCreator__

#include "GlobalConfig.h"
#include "Poco/Data/SessionFactory.h"
#include "Poco/Data/Session.h"
#include "Poco/Data/SQLite/Connector.h"
#include "Poco/StringTokenizer.h"
#include "Poco/File.h"
#include "dbstructure.h"
#include "Poco/Exception.h"
#include "..\client\log.h"

using namespace Poco::Data;
using Poco::StringTokenizer;
using Poco::File;
using Poco::Exception;
using namespace std;

class DBCreator
{
public:
    DBCreator(const string name, const string schema)
    {
        db_name = name;
        db_schema = schema;
    }

    bool CheckDatabase();
private:
    bool CreateDatabase();
    string db_name;
    string db_schema;
};


bool DBCreator::CreateDatabase()
{
    FLogger.trace("creating data base...");
    try
    {
        // register SQLite connector
        Poco::Data::SQLite::Connector::registerConnector();
        // create a session
        Session session("SQLite", db_name);

        StringTokenizer st(db_schema, "\n");

        StringTokenizer::Iterator it;

        for(it = st.begin(); it != st.end(); it++)
        {
            FLogger.information("executing : " + *it->c_str());
            session << it->c_str(),now;
        }
    }
    catch (Exception& e)
    {
        FLogger.information("exception occurred while creating database...");
        FLogger.information(e.what());
        FLogger.information(e.displayText());
        return false;
    }

    FLogger.trace("creating database successfully...");
    return true;
}

bool DBCreator::CheckDatabase()
{
    if (db_name == "" || db_schema == "")
    {
        FLogger.trace("invalid database name and schema...");
        return false;
    }

    File db(db_name);
    bool ret = false;

    if (!db.exists())
    {
        FLogger.trace("database doesnot exist, create it...");
        if(!CreateDatabase())
        {
            FLogger.trace("create database failed...");
            db.remove();
            return false;
        }
        FLogger.trace("database created successfully...");
    }

    return true;
}

#endif